package com.example.campus.dao.table_gateway.shiro;

import com.example.campus.dao.model.shiro.Role;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;

import java.util.HashSet;
import java.util.List;
import java.util.Set;


@Mapper
public interface RoleMapper {
    @Insert("insert into t_sys_role " +
            "(`name`, `description`) " +
            "VAlUES " +
            "(#{name}, #{description})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void addRole(Role role);

    @Select("Select * from t_sys_role")
    Set<Role> getAllRoles();

    @Select("Select * from t_sys_role where id=#{id}")
    Role getRoleById(@Param("id") long id);

    @Update("<script>" +
            "UPDATE t_sys_role " +
            "<set>" +
            "<if test='name != null'>`name` = #{name}, </if>"+
            "<if test='description != null'>`description` = #{description} </if>"+
            "</set>"+
            "where id = #{id}"+
            "</script>")
    void updateRoleById(Role role);

    @Delete("delete from t_sys_role where id = #{id}")
    void deleteRoleById(@Param("id") long id);


    @Results({
//            外键
            @Result(property = "id", column = "id"),
            @Result(property = "name", column = "role_name"),
            @Result(property = "description", column = "description"),
            @Result(property = "permissions", javaType = HashSet.class,
                    /*参数, 传给下面的查询方法 */ column = "p_id",
            many = @Many(select = "com.example.campus.dao.table_gateway.shiro.PermissionMapper.getPermissionById",
                    columnPrefix = "p_", fetchType = FetchType.LAZY))
    })
    @Select("SELECT r.id AS id, r.name AS role_name, r.description AS description, " +
                    "p.id AS p_id, p.name AS p_name, p.code AS p_code, p.url AS p_url, p.order AS p_order " +
            "FROM t_sys_role r " +
            "JOIN t_sys_role_permission rp " +
            "ON r.id = rp.role_id " +
            "JOIN t_sys_permission p " +
            "ON rp.perm_id = p.id " +
            "where r.id = #{id} ")
    Role getRoleWithPermissionsByRoleId(@Param("id")long id);
}
